package com.ruoyi.WELD.controller;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.WELD.domain.Welding;
import lombok.Getter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeldingImportListener extends AnalysisEventListener<Map<Integer, String>> {

    @Getter
    private final List<Welding> list = new ArrayList<>();
    private Map<Integer, String> headerMap = new HashMap<>();

    private static final Map<String, String> COLUMN_MAP = new HashMap<>();
    static {
        // 坐标
        COLUMN_MAP.put("焊点坐标(X)", "x");
        COLUMN_MAP.put("LOCX", "x");
        COLUMN_MAP.put("焊点坐标(Y)", "y");
        COLUMN_MAP.put("LOCY", "y");
        COLUMN_MAP.put("焊点坐标(Z)", "z");
        COLUMN_MAP.put("LOCZ", "z");

        // 基本信息
        COLUMN_MAP.put("工位", "station");
        COLUMN_MAP.put("Product", "product");
        COLUMN_MAP.put("焊点号(五位焊点号)", "solderJoint");
        COLUMN_MAP.put("焊点号", "solderJoint");
        COLUMN_MAP.put("数模焊点号", "sjNumber");
        COLUMN_MAP.put("JEID", "sjNumber");
        COLUMN_MAP.put("焊枪编号", "torchNumber");
        COLUMN_MAP.put("机器人名称", "robot");
        COLUMN_MAP.put("额定压力", "ratedPressure");
        COLUMN_MAP.put("规范号", "gaugeNumber");
        COLUMN_MAP.put("电极形式", "electrodeForm");

        // 材质1
        COLUMN_MAP.put("JCPN1", "jcpn1");
        COLUMN_MAP.put("材质1", "material1");
        COLUMN_MAP.put("material1", "material1");
        COLUMN_MAP.put("材质1厚度(mm)", "materialThickness1");
        COLUMN_MAP.put("thickness1", "materialThickness1");
        COLUMN_MAP.put("涂胶1", "gumming1");

        // 材质2
        COLUMN_MAP.put("JCPN2", "jcpn2");
        COLUMN_MAP.put("材质2", "material2");
        COLUMN_MAP.put("material2", "material2");
        COLUMN_MAP.put("材质2厚度(mm)", "materialThickness2");
        COLUMN_MAP.put("thickness2", "materialThickness2");
        COLUMN_MAP.put("涂胶2", "gumming2");

        // 材质3
        COLUMN_MAP.put("JCPN3", "jcpn3");
        COLUMN_MAP.put("材质3", "material3");
        COLUMN_MAP.put("material3", "material3");
        COLUMN_MAP.put("材质3厚度(mm)", "materialThickness3");
        COLUMN_MAP.put("thickness3", "materialThickness3");
        COLUMN_MAP.put("涂胶3", "gumming3");

        // 材质4
        COLUMN_MAP.put("JCPN4", "jcpn4");
        COLUMN_MAP.put("材质4", "material4");
        COLUMN_MAP.put("material4", "material4");
        COLUMN_MAP.put("材质4厚度(mm)", "materialThickness4");
        COLUMN_MAP.put("thickness4", "materialThickness4");

        // 工艺参数
        COLUMN_MAP.put("压力(N)", "stress");
        COLUMN_MAP.put("预压时间(ms)", "preloadingTime");
        COLUMN_MAP.put("加压时间(ms)", "pressurizationTime");
        COLUMN_MAP.put("预热时间(ms)", "preheatingTime");
        COLUMN_MAP.put("预热电流(kA)", "preheatingCurrent");
        COLUMN_MAP.put("冷却时间1(ms)", "coolingTime");
        COLUMN_MAP.put("递增时间(ms)", "incrementalTime");
        COLUMN_MAP.put("起始电流(KA)", "startingCurrent");
        COLUMN_MAP.put("焊接时间(ms)", "weldingTime");
        COLUMN_MAP.put("焊接电流(kA)", "weldingCurrent");
        COLUMN_MAP.put("冷却时间2(ms)", "coolingTime1");
        COLUMN_MAP.put("递减时间(ms)", "declineTime");
        COLUMN_MAP.put("终止电流(KA)", "terminationCurrent");
        COLUMN_MAP.put("脉冲次数", "pulseFrequency");
        COLUMN_MAP.put("冷却时间3(ms)", "coolingTime2");
        COLUMN_MAP.put("回火时间(ms)", "temperingTime");
        COLUMN_MAP.put("回火电流(kA)", "temperingCurrent");
        COLUMN_MAP.put("保持时间(ms)", "holdTime");
        COLUMN_MAP.put("频率", "parametricForm");
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headerMap = headMap;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        Welding welding = new Welding();
        for (Map.Entry<Integer, String> entry : data.entrySet()) {
            Integer colIndex = entry.getKey();
            String cellValue = entry.getValue();
            String columnName = headerMap.get(colIndex);
            if (columnName == null || cellValue == null) continue;

            switch (COLUMN_MAP.getOrDefault(columnName.trim(), "")) {
                case "x":
                    welding.setX(parseDouble(cellValue));
                    break;
                case "y":
                    welding.setY(parseDouble(cellValue));
                    break;
                case "z":
                    welding.setZ(parseDouble(cellValue));
                    break;
                case "station":
                    welding.setStation(cellValue);
                    break;
                case "product":
                    welding.setProduct(parseString(cellValue));
                    break;
                case "solderJoint":
                    welding.setSolderJoint(cellValue);
                    break;
                case "sjNumber":
                    welding.setSjNumber(cellValue);
                    break;
                case "torchNumber":
                    welding.setTorchNumber(cellValue);
                    break;
                case "robot":
                    welding.setRobot(cellValue);
                    break;
                case "ratedPressure":
                    welding.setRatedPressure(cellValue);
                    break;
                case "gaugeNumber":
                    welding.setGaugeNumber(parseInteger(cellValue));
                    break;
                case "electrodeForm":
                    welding.setElectrodeForm(cellValue);
                    break;
                case "jcpn1":
                    welding.setJcpn1(parseString(cellValue));
                    break;
                case "material1":
                    welding.setMaterial1(parseString(cellValue));
                    break;
                case "materialThickness1":
                    welding.setMaterialThickness1(parseDouble(cellValue));
                    break;
                case "gumming1":
                    welding.setGumming1(parseString(cellValue));
                    break;
                case "jcpn2":
                    welding.setJcpn2(parseString(cellValue));
                    break;
                case "material2":
                    welding.setMaterial2(parseString(cellValue));
                    break;
                case "materialThickness2":
                    welding.setMaterialThickness2(parseDouble(cellValue));
                    break;
                case "gumming2":
                    welding.setGumming2(parseString(cellValue));
                    break;
                case "jcpn3":
                    welding.setJcpn3(parseString(cellValue));
                    break;
                case "material3":
                    welding.setMaterial3(parseString(cellValue));
                    break;
                case "materialThickness3":
                    welding.setMaterialThickness3(parseDouble(cellValue));
                    break;
                case "gumming3":
                    welding.setGumming3(parseString(cellValue));
                    break;
                case "jcpn4":
                    welding.setJcpn4(parseString(cellValue));
                    break;
                case "material4":
                    welding.setMaterial4(parseString(cellValue));
                    break;
                case "materialThickness4":
                    welding.setMaterialThickness4(parseDouble(cellValue));
                    break;
                case "stress":
                    welding.setStress(cellValue);
                    break;
                case "preloadingTime":
                    welding.setPreloadingTime(parseDouble(cellValue));
                    break;
                case "pressurizationTime":
                    welding.setPressurizationTime(parseDouble(cellValue));
                    break;
                case "preheatingTime":
                    welding.setPreheatingTime(parseDouble(cellValue));
                    break;
                case "preheatingCurrent":
                    welding.setPreheatingCurrent(parseDouble(cellValue));
                    break;
                case "coolingTime":
                    welding.setCoolingTime(parseDouble(cellValue));
                    break;
                case "incrementalTime":
                    welding.setIncrementalTime(parseDouble(cellValue));
                    break;
                case "startingCurrent":
                    welding.setStartingCurrent(parseDouble(cellValue));
                    break;
                case "weldingTime":
                    welding.setWeldingTime(parseDouble(cellValue));
                    break;
                case "weldingCurrent":
                    welding.setWeldingCurrent(parseDouble(cellValue));
                    break;
                case "coolingTime1":
                    welding.setCoolingTime1(parseDouble(cellValue));
                    break;
                case "declineTime":
                    welding.setDeclineTime(parseDouble(cellValue));
                    break;
                case "terminationCurrent":
                    welding.setTerminationCurrent(parseDouble(cellValue));
                    break;
                case "pulseFrequency":
                    welding.setPulseFrequency(parseDouble(cellValue));
                    break;
                case "coolingTime2":
                    welding.setCoolingTime2(parseDouble(cellValue));
                    break;
                case "temperingTime":
                    welding.setTemperingTime(parseDouble(cellValue));
                    break;
                case "temperingCurrent":
                    welding.setTemperingCurrent(parseDouble(cellValue));
                    break;
                case "holdTime":
                    welding.setHoldTime(parseDouble(cellValue));
                    break;
                case "parametricForm":
                    welding.setParametricForm(cellValue);
                    break;
                default:
                    // 未匹配列可忽略或日志
                    break;
            }
        }
        System.out.println(">>> 第" + context.readRowHolder().getRowIndex()
                + "行，station=" + welding.getStation());
        if (isEmptyRow(welding)) {
            return;   // 不加入 list
        }
        list.add(welding);
    }

    /** 核心业务字段全为 null 则认为空行 */
    private boolean isEmptyRow(Welding w) {
        return w.getMaterial1() == null
                && w.getMaterial2() == null
                && w.getMaterial3() == null;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 如需在此批量保存，可调用 service
    }

    private Double parseDouble(String val) {
        if (val == null || val.trim().isEmpty() || "null".equalsIgnoreCase(val)) return null;
        // 匹配第一个连续的数字（可含小数点）
        java.util.regex.Matcher matcher = java.util.regex.Pattern
                .compile("\\d+(\\.\\d+)?")
                .matcher(val.trim());
        if (matcher.find()) {
            try {
                return Double.parseDouble(matcher.group());
            } catch (Exception ignored) {}
        }
        return null;
    }

    private Integer parseInteger(String val) {
        if (val == null || val.trim().isEmpty() || "null".equalsIgnoreCase(val)) return null;
        java.util.regex.Matcher matcher = java.util.regex.Pattern
                .compile("\\d+")
                .matcher(val.trim());
        if (matcher.find()) {
            try {
                return Integer.parseInt(matcher.group());
            } catch (Exception ignored) {}
        }
        return null;
    }
    private String parseString(String val) {
        if (val == null) return null;
        val = val.trim();
        // 只有一个斜杠（/）或空字符串 → 返回 null
        if (val.isEmpty() || "/".equals(val) || "null".equalsIgnoreCase(val)) {
            return null;
        }
        return val;
    }
}